package com.frinder.base.utils;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.stream.IntStream;

import static java.util.stream.Collectors.toList;

/**
 * @ClassName CollectUtils
 * @Description 集合辅助类
 * @Author frinder
 * @Date 2019/4/2 18:25
 * @Verion 1.0
 */
public class CollectUtils {

    /**
     * @Author frinder
     * @Description 对矩阵集合进行转置
     * @Date 2019/4/2 18:27
     * @Param [matrix]
     * @Return java.util.List<java.util.List>
     */
    public static <E> List<List<E>> transform(List<List<E>> matrix) {
        int maxSize = matrix.parallelStream().mapToInt(List::size).max().orElse(0);
        return IntStream.range(0, maxSize)
                .mapToObj(i -> matrix.parallelStream().filter(s -> s.size() > i).map(s -> s.get(i)).collect(toList()))
                .collect(toList());
    }

    /**
     * @Author frinder
     * @Description 将集合平均 n 等分
     * @Date 2019/4/7 15:22
     * @Param [source, n]
     * @Return java.util.List<java.util.List>
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = Lists.newArrayList();
        //(先计算出余数)
        int remainder = source.size() % n;
        //然后是商
        int number = source.size() / n;
        //偏移量
        int offset = 0;
        for (int i = 0; i < n; i++) {
            List<T> value;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }

    public static void main(String[] args) {
        List<Integer> a = Lists.newArrayList(1, 1, 1, 2, 2, 2, 3, 3, 3);
        System.out.println(averageAssign(a, 2));
    }

}
